package org.edu.modules.enroll.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.edu.common.api.vo.Result;
import org.edu.modules.enroll.entity.VeDictQuarter;
import org.edu.modules.enroll.entity.VeZsPtemplet;
import org.edu.modules.enroll.entity.VeZsRegistration;
import org.edu.modules.enroll.service.VeDictQuarterService;
import org.edu.modules.enroll.service.VeZsPtempletService;
import org.edu.modules.enroll.service.VeZsRegistrationService;
import org.edu.modules.enroll.vo.VeZsRegistrationVo;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.List;
import java.io.PrintStream;
import java.io.FileOutputStream;
import gui.ava.html.image.generator.HtmlImageGenerator;
import org.edu.modules.enroll.tools.HtmlImgGenerator;


/**
 * 通知书模板打印
 * @author yhx
 */
@Api(tags = "通知书模板打印")
@RestController
@RequestMapping("enroll/admissionPrint")
public class AdmissionPrintController {

    @Resource
    private VeDictQuarterService veDictQuarterService;

    @Resource
    private VeZsRegistrationService veZsRegistrationService;

    @Resource
    private OSS ossClient;

    @Resource
    private VeZsPtempletService veZsPtempletService;

    @ApiOperation("获取模板对象")
    @PostMapping("/getPrintCode")
    public Result<?> getPrintCode(){

        QueryWrapper<VeZsPtemplet> wrapper = new QueryWrapper<>();
        wrapper.eq("status",1);
        List<VeZsPtemplet> list = veZsPtempletService.list(wrapper);

        return Result.OK(list);
    }

    @ApiOperation("获取通知书打印的学生集合")
    @PostMapping("/select")
    public Result<?> getAdmissionPrintStuList(@ApiParam("专业部ID") @RequestParam("facultyId") Long facultyId,
                                           @ApiParam("专业ID") @RequestParam("specialtyId") Long specialtyId,
                                           @ApiParam("关键词") @RequestParam("keyword") String keyword,
                                           @ApiParam("查询条件") @RequestParam("condit") String condit,
                                           @ApiParam("当前页") @RequestParam("currentPage") Integer currentPage,
                                           @ApiParam("条数") @RequestParam("pageSize") Integer pageSize,
                                           @ApiParam("是否录取") @RequestParam("isPrint") Integer isPrint){


        //获取当前招生季ID
        QueryWrapper<VeDictQuarter> quarterWrapper = new QueryWrapper<VeDictQuarter>().eq("isCur", 1);
        VeDictQuarter one = veDictQuarterService.getOne(quarterWrapper);
        if(one == null){
            return Result.error("列表加载失败：当前招生季未启用！");
        }
        Integer quarterId = one.getId();

        if (facultyId == 0) {
            facultyId = null;
        }
        if (specialtyId == 0) {
            specialtyId = null;
        }
        if (isPrint == 2) {
            isPrint = null;
        }

        Integer current = (currentPage - 1) * pageSize;

        List<VeZsRegistrationVo> list = veZsRegistrationService.getAdmissionPrint(quarterId, facultyId, specialtyId, keyword, condit, current, pageSize, isPrint);

        //条件构造器
        QueryWrapper<VeZsRegistration> wrapper = new QueryWrapper<>();
        wrapper.eq("isCheck",1);
        wrapper.eq("isAdmit",1);
        wrapper.eq("isReport",0);
        wrapper.eq("ZSJ", quarterId);

        //判断打印次数
        if (isPrint != null) {
            if(isPrint == 0){
                wrapper.eq("enrollNum", 0);
            }else if(isPrint == 1){
                //gt等价>   lt等价<   ge等价>=   le等价<=
                wrapper.gt("enrollNum",0);
            }
        }

        if (facultyId != null) {
            wrapper.eq("falId", facultyId);
        }

        if (specialtyId != null) {
            wrapper.eq("specId", specialtyId);
        }

        if (condit != null && keyword != null && (!keyword.trim().equals(""))) {
            wrapper.like(condit, keyword);
        }

        //查询总数
        Integer count = veZsRegistrationService.list(wrapper).size();

        //返回前端搜索结果
        HashMap<String, Object> map = new HashMap<>();
        map.put("list", list);
        map.put("count", count);

        return Result.OK(map);
    }


    @ApiOperation("生成二维码")
    @PostMapping("/createQRCode")
    public Result<?> createQRCode(@ApiParam("拼接的ID字符串") @RequestParam(value = "ids") String ids){

        //切割字符串
        String[] split = ids.split(",");

        for(String sp : split){
            Long id = Long.parseLong(sp);
            //获取对应ID的信息
            VeZsRegistration stu = veZsRegistrationService.getById(id);

            //二维码图片名称
            String QR_CODE_IMAGE_PATH = stu.getXm()+"_"+stu.getBmh()+".png";

            String sex = stu.getXbm().equals("1") ? "男":"女";

            //拼接二维码内容
            String text = "姓名："+stu.getXm()+"\n"+"性别："+sex+"\n"+"身份证号："+stu.getSfzh()+"\n"+"所属专业部："+stu.getYxmc()+"\n"+"所属专业："+stu.getZymc()+"\n"+"入学年份："+stu.getRxnf();


            try {
                String  HTMLfName = QR_CODE_IMAGE_PATH.trim();
                System.out.println("1 HTMLfName:"+HTMLfName);
                String temp[] = HTMLfName.split("\\\\"); //split里面必须是正则表达式，"\\"的作用是对字符串转义，其中split("\\\\")的作用是：按照"\\"为分隔符，将路径截取，并存入数组，
                String tmpfileName = temp[temp.length-1];//(取出最后一个)
                System.out.println("2 tmpfileName:"+tmpfileName);
                String htmlsname=stu.getSfzh()+".html";
                String imagesname=stu.getSfzh()+".png";
                System.out.println("3 imagesname:"+imagesname);
                String QR_HTML_PATH=QR_CODE_IMAGE_PATH.replace(tmpfileName,htmlsname);
                String QR_Image_PATH=QR_CODE_IMAGE_PATH.replace(tmpfileName,imagesname);
                System.out.println("4 QR_Image_PATH:"+QR_Image_PATH);
                File HtmlFile = new File(QR_HTML_PATH);//创建文件
                if(HtmlFile.exists()) {//删除原来的旧文件
                    HtmlFile.delete();
                }
                PrintStream printStream = new PrintStream(new FileOutputStream(HtmlFile));
                StringBuilder stringHtml = new StringBuilder();
                //输入HTML文件内容
                stringHtml.append("<!DOCTYPE html>");
                stringHtml.append("<html>");
                stringHtml.append("<head>");
                stringHtml.append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=gbk\"/>");
                stringHtml.append("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0\">");
                stringHtml.append("<title>二维码识别详情</title>");
                stringHtml.append("</head>");
                stringHtml.append("<body>");
                stringHtml.append("<div style=\"padding: 100px 80px;\">");
                stringHtml.append("<div style=\"border: 3px solid navy;\">");
                stringHtml.append("<div style=\"background: blue; color: white; text-align: center; font-size: 25px; height: 100px; line-height: 100px;\">");
                stringHtml.append("<span>二维码识别</span>");
                stringHtml.append("</div>");
                stringHtml.append("<div style=\"background: white; text-align: center; padding: 60px 30px;\">");
                stringHtml.append("<div style=\"font-size: 15px; color: black;\">");
                stringHtml.append("姓名: "+stu.getXm()+" ");
                stringHtml.append("</div>");
                stringHtml.append("<div style=\"font-size: 15px; color: black;\">");
                stringHtml.append("性别: "+sex+"");
                stringHtml.append("</div>");
                stringHtml.append("<div style=\"font-size: 15px; color: black;\">");
                stringHtml.append("身份证号: "+stu.getSfzh()+" ");
                stringHtml.append("</div>");
                stringHtml.append("<div style=\"font-size: 15px; color: black;\">");
                stringHtml.append("所属专业部: "+stu.getYxmc()+" ");
                stringHtml.append("</div>");
                stringHtml.append("<div style=\"font-size: 15px; color: black;\">");
                stringHtml.append("所属专业: "+stu.getZymc()+"");
                stringHtml.append("</div>");
                stringHtml.append("<div style=\"font-size: 15px; color: black;\">");
                stringHtml.append("入学年份: "+stu.getYxmc()+"");
                stringHtml.append("</div>");
                stringHtml.append("</div>");
                stringHtml.append("</div>");
                stringHtml.append("</div>");
                stringHtml.append("</body>");
                stringHtml.append("</html>");
                printStream.println(stringHtml.toString());


                StringBuilder stringHtmltmp = new StringBuilder();
                stringHtmltmp.append("<div style=\"font-size: 25px; color: black; margin: 5px 0px; text-align: left;\">");
                stringHtmltmp.append("姓名: "+stu.getXm()+" ");
                stringHtmltmp.append("</div>");
                stringHtmltmp.append("<div style=\"font-size: 25px; color: black; margin: 5px 0px; text-align: left;\">");
                stringHtmltmp.append("性别: "+sex+"");
                stringHtmltmp.append("</div>");
                stringHtmltmp.append("<div style=\"font-size: 25px; color: black; margin: 5px 0px;text-align: left;\">");
                stringHtmltmp.append("身份证号: "+stu.getSfzh()+" ");
                stringHtmltmp.append("</div>");
                stringHtmltmp.append("<div style=\"font-size: 25px; color: black; margin: 5px 0px;text-align: left;\">");
                stringHtmltmp.append("所属专业部: "+stu.getYxmc()+" ");
                stringHtmltmp.append("</div>");
                stringHtmltmp.append("<div style=\"font-size: 25px; color: black; margin: 5px 0px;text-align: left;\">");
                stringHtmltmp.append("所属专业: "+stu.getZymc()+"");
                stringHtmltmp.append("</div>");
                stringHtmltmp.append("<div style=\"font-size: 25px; color: black; margin: 5px 0px;text-align: left;\">");
                stringHtmltmp.append("入学年份: "+stu.getYxmc()+"");
                stringHtmltmp.append("</div>");
                HtmlImgGenerator imageGenerator = new HtmlImgGenerator();
                imageGenerator.html2Img(stringHtmltmp.toString(),QR_Image_PATH);
                File HtmlimageFile= new File(QR_Image_PATH);
                //上传HTML文件
                PutObjectResult resulthtml = ossClient.putObject("csm-bucket","qrcode/"+QR_HTML_PATH,HtmlFile);
                System.out.println("5 resulthtml:"+resulthtml);
                PutObjectResult resultimage = ossClient.putObject("csm-bucket","qrcode/"+QR_Image_PATH,HtmlimageFile);
                System.out.println("5 resultimage:"+resultimage);
                text ="https://csm-bucket.oss-cn-hangzhou.aliyuncs.com/qrcode/"+imagesname;
                System.out.println("6 text:"+text);
            }  catch (Exception e) {
                System.out.println("Could not generate QR_HTML_PATH, IOException :: " + e.getMessage());
            }






            //生成二维码
            try {
                generateQRCodeImage(text, 350, 350, QR_CODE_IMAGE_PATH);
            } catch (WriterException e) {
                System.out.println("Could not generate QR Code, WriterException :: " + e.getMessage());
            } catch (IOException e) {
                System.out.println("Could not generate QR Code, IOException :: " + e.getMessage());
            }

            //获取文件
            File file = new File(QR_CODE_IMAGE_PATH);

            // meta设置请求头
            ObjectMetadata meta = new ObjectMetadata();
            meta.setContentType("image/jpg");

            //上传文件到指定的存储空间  第一个参数 bucketName  第二个参数 OSS存储路径  第三个参数 要上传的文件
            PutObjectResult result = ossClient.putObject("csm-bucket","qrcode/"+QR_CODE_IMAGE_PATH,file);

            //存储qrCode路径
            UpdateWrapper<VeZsRegistration> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("id",stu.getId());
            updateWrapper.set("qrcodeUrl",QR_CODE_IMAGE_PATH);

            boolean update = veZsRegistrationService.update(updateWrapper);

            System.out.println("update:"+update);

        }

        return Result.OK("生成二维码成功！");
    }

    /**
     * 生成二维码的方法
     * @param text
     * @param width
     * @param height
     * @param filePath
     * @throws WriterException
     * @throws IOException
     */
    private void generateQRCodeImage(String text, int width, int height, String filePath) throws WriterException, IOException {
        //解决中文乱码问题:
        text = new String(text.getBytes("UTF-8"), "ISO-8859-1");

        QRCodeWriter qrCodeWriter = new QRCodeWriter();


        BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);


        Path path = FileSystems.getDefault().getPath(filePath);

        MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);

    }

    @ApiOperation("下载二维码")
    @PostMapping("/downloadQRCode")
    public Result<?> downloadQRCode(@ApiParam("ID") @RequestParam(value = "id") Long id){

        System.out.println("id:"+id);

        //查找对应的ID是否已经生成二维码
        VeZsRegistration stu = veZsRegistrationService.getById(id);
        String url = stu.getQrcodeUrl();

        //未生成二维码 返回错误提示
        if(url == null || url == ""){
            return Result.error("该学生未生成二维码！");
        }

        return Result.OK(url);
    }

}
